#!/bin/bash

export LANG=en_US.UTF-8
PROC_FILE="$(dirname $0)/proc.list"
LOG_PATH="/var/log/monitor"
LOG_NAME="proc"
INTERVAL=60

function Init {
    local self_count=$(pgrep -cx "$(basename $0)")
    [ 0 -eq $? ] || exit 1
    [ 1 -eq $self_count ] || exit 1
    mkdir -p $LOG_PATH || exit 1
}

function Log {
    local msg="$1"
    local log_time="$(date +'%F %T')"
    local log_file="$LOG_PATH/$LOG_NAME-${log_time% *}.log"
    echo "$log_time $msg" >> $log_file
    cd $LOG_PATH && ls ${LOG_NAME}-* 2>/dev/null \
        | head -n -7 | xargs rm -f
}

function GetProcInfo {
    local line="$1"
    local class="${line%% *}"
    local proc="${line#* }"
    local stat_code=1
    local stat=
    if [ 'service' = "$class" ]; then
        stat="$(systemctl status $proc \
            | grep -m 1 '^   Active:' \
            | awk '{print $2}')"
        [ 'active' = "$stat" ] && stat_code=0
        [ -z "$stat" ] && stat="unknown"
    else
        pgrep -f "$proc" &> /dev/null && stat_code=0 \
            && stat='running' || stat='stopped'
    fi
    echo "$class#$proc#$stat#$stat_code"
}

function Main {
    local line=
    sleep $INTERVAL
    while read line; do
        Log "$(GetProcInfo "$line")"
    done < $PROC_FILE
}

# start
Init
Main

